/**
 * Copyright © 2016-2025 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.terracloud.server.dao.sql.log;

import com.terracloud.server.common.data.log.LogLevel;
import com.terracloud.server.common.data.log.LogType;
import com.terracloud.server.common.data.log.LogStatus;
import com.terracloud.server.common.data.log.TerminalLog;
import com.terracloud.server.common.data.id.DeviceId;
import com.terracloud.server.common.data.id.TenantId;
import com.terracloud.server.common.data.id.TerminalLogId;
import com.terracloud.server.common.data.page.PageData;
import com.terracloud.server.common.data.page.TimePageLink;
import com.terracloud.server.dao.DaoUtil;
import com.terracloud.server.dao.log.TerminalLogDao;
import com.terracloud.server.dao.model.sql.TerminalLogEntity;
import com.terracloud.server.dao.sql.JpaAbstractDao;
import com.terracloud.server.dao.util.SqlDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Component
@Slf4j
@SqlDao
public class JpaTerminalLogDao extends JpaAbstractDao<TerminalLogEntity, TerminalLog> implements TerminalLogDao {

    @Autowired
    private TerminalLogRepository terminalLogRepository;

    @Override
    protected Class<TerminalLogEntity> getEntityClass() {
        return TerminalLogEntity.class;
    }

    @Override
    protected JpaRepository<TerminalLogEntity, UUID> getRepository() {
        return terminalLogRepository;
    }

    @Override
    @Transactional
    public TerminalLog save(TerminalLog terminalLog) {
        if (terminalLog.getTenantId() != null) {
            return save(terminalLog.getTenantId(), terminalLog);
        } else {
            // 如果没有租户ID，则创建一个默认的TenantId
            return save(TenantId.SYS_TENANT_ID, terminalLog);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public TerminalLog findById(TerminalLogId terminalLogId) {
        // 使用系统租户ID作为默认值
        return findById(TenantId.SYS_TENANT_ID, terminalLogId.getId());
    }

    @Override
    @Transactional
    public void removeById(TerminalLogId terminalLogId) {
        // 使用系统租户ID作为默认值
        removeById(TenantId.SYS_TENANT_ID, terminalLogId.getId());
    }

    @Override
    @Transactional(readOnly = true)
    public PageData<TerminalLog> findByDeviceId(TenantId tenantId, DeviceId deviceId, TimePageLink pageLink) {
        log.debug("DAO: Finding terminal logs by tenantId={} and deviceId={} with pageLink={}", tenantId, deviceId, pageLink);
        PageData<TerminalLog> result = DaoUtil.toPageData(
                terminalLogRepository.findByDeviceId(
                        tenantId.getId(), 
                        deviceId.getId(),
                        pageLink.getStartTime(),
                        pageLink.getEndTime(),
                        DaoUtil.toPageable(pageLink)));
        log.debug("DAO: Found {} terminal logs", result.getTotalElements());
        return result;
    }

    @Override
    @Transactional(readOnly = true)
    public PageData<TerminalLog> findByTenantId(TenantId tenantId, TimePageLink pageLink) {
        log.debug("DAO: Finding terminal logs by tenantId={} with pageLink={}", tenantId, pageLink);
        PageData<TerminalLog> result = DaoUtil.toPageData(
                terminalLogRepository.findByTenantId(
                        tenantId.getId(),
                        pageLink.getStartTime(),
                        pageLink.getEndTime(),
                        DaoUtil.toPageable(pageLink)));
        log.debug("DAO: Found {} terminal logs", result.getTotalElements());
        return result;
    }

    @Override
    @Transactional(readOnly = true)
    public PageData<TerminalLog> findByTenantIdAndType(TenantId tenantId, LogType logType, TimePageLink pageLink) {
        log.debug("DAO: Finding terminal logs by tenantId={} and logType={} with pageLink={}", tenantId, logType, pageLink);
        PageData<TerminalLog> result = DaoUtil.toPageData(
                terminalLogRepository.findByTenantIdAndType(
                        tenantId.getId(), 
                        logType,
                        pageLink.getStartTime(),
                        pageLink.getEndTime(),
                        DaoUtil.toPageable(pageLink)));
        log.debug("DAO: Found {} terminal logs", result.getTotalElements());
        return result;
    }

    @Override
    @Transactional(readOnly = true)
    public PageData<TerminalLog> findByTenantIdAndLevel(TenantId tenantId, LogLevel logLevel, TimePageLink pageLink) {
        log.debug("DAO: Finding terminal logs by tenantId={} and logLevel={} with pageLink={}", tenantId, logLevel, pageLink);
        PageData<TerminalLog> result = DaoUtil.toPageData(
                terminalLogRepository.findByTenantIdAndLevel(
                        tenantId.getId(), 
                        logLevel,
                        pageLink.getStartTime(),
                        pageLink.getEndTime(),
                        DaoUtil.toPageable(pageLink)));
        log.debug("DAO: Found {} terminal logs", result.getTotalElements());
        return result;
    }

    @Override
    @Transactional(readOnly = true)
    public PageData<TerminalLog> findByTenantIdAndDeviceIdAndType(TenantId tenantId, DeviceId deviceId, LogType logType, TimePageLink pageLink) {
        log.debug("DAO: Finding terminal logs by tenantId={}, deviceId={} and logType={} with pageLink={}", tenantId, deviceId, logType, pageLink);
        PageData<TerminalLog> result = DaoUtil.toPageData(
                terminalLogRepository.findByTenantIdAndDeviceIdAndType(
                        tenantId.getId(), 
                        deviceId.getId(), 
                        logType,
                        pageLink.getStartTime(),
                        pageLink.getEndTime(),
                        DaoUtil.toPageable(pageLink)));
        log.debug("DAO: Found {} terminal logs", result.getTotalElements());
        return result;
    }

    @Override
    @Transactional(readOnly = true)
    public PageData<TerminalLog> findByTenantIdAndDeviceIdAndLevel(TenantId tenantId, DeviceId deviceId, LogLevel logLevel, TimePageLink pageLink) {
        log.debug("DAO: Finding terminal logs by tenantId={}, deviceId={} and logLevel={} with pageLink={}", tenantId, deviceId, logLevel, pageLink);
        PageData<TerminalLog> result = DaoUtil.toPageData(
                terminalLogRepository.findByTenantIdAndDeviceIdAndLevel(
                        tenantId.getId(), 
                        deviceId.getId(), 
                        logLevel,
                        pageLink.getStartTime(),
                        pageLink.getEndTime(),
                        DaoUtil.toPageable(pageLink)));
        log.debug("DAO: Found {} terminal logs", result.getTotalElements());
        return result;
    }

    @Override
    @Transactional(readOnly = true)
    public long countByProcessStatus(TenantId tenantId, LogStatus processStatus) {
        return terminalLogRepository.countByProcessStatus(tenantId.getId(), processStatus);
    }

    @Override
    @Transactional(readOnly = true)
    public long countByCritical(TenantId tenantId, boolean isCritical) {
        return terminalLogRepository.countByCritical(tenantId.getId());
    }

    @Override
    @Transactional(readOnly = true)
    public long countByDurationGreaterThan(TenantId tenantId, long duration) {
        return terminalLogRepository.countByDurationGreaterThan(tenantId.getId(), duration);
    }
}